import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/bloc/my/UserActivtyBloc.dart';
import 'package:qgchat/common/class/videoCall/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/UserAcitvtyModel.dart';
import 'package:qgchat/http/models/userInfoModel.dart';
import 'package:qgchat/states/states_model/socket.dart';
import 'package:qgchat/widgets/avatar.dart';
import 'package:qgchat/widgets/easyRefreshWidget.dart';
import 'package:qgchat/widgets/line.dart';
import 'package:qgchat/widgets/tipsDialog.dart';

///
/// 动态页面
/// page动态
///

class Useractivity extends StatefulWidget {
  @override
  _UseractivityState createState() => _UseractivityState();
}

class _UseractivityState extends State<Useractivity> {
  final blog = UserActivtyBloc();

  String pageType; // 页面类型

// -----------------------------------------------------------------------------

  /// 动态列表
  Widget attentionOrFansList() {
    final UserActivtyBloc bloc = BlocProvider.of<UserActivtyBloc>(context);
    Stream blocStream;
    blocStream = bloc.outFansStream;
    return StreamBuilder<List<UserAcitvtyModel>>(
      stream: blocStream,
      initialData: [],
      builder: (BuildContext context,
          AsyncSnapshot<List<UserAcitvtyModel>> snapshot) {
        return Text(snapshot.toString());
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return stateBuilder(context, 'user', (user) {
      UserInfoModel userInfo = user.info;
      if (userInfo != null) {
        return BlocProvider<UserActivtyBloc>(
          bloc: blog,
          child: Scaffold(
            body: Container(
              width: w100(context),
              padding: EdgeInsets.symmetric(horizontal: px(30)),
              color: Colors.white,
              child: _AttentionOrFansList(),
            ),
          ),
        );
      } else {
        return Scaffold(
          body: Container(color: Colors.white),
        );
      }
    });
  }
}

/// 列表
class _AttentionOrFansList extends StatefulWidget {
  _AttentionOrFansList({Key key}) : super(key: key);

  @override
  __AttentionOrFansListState createState() => __AttentionOrFansListState();
}

class __AttentionOrFansListState extends State<_AttentionOrFansList> {
//  String pageType = 'fans'; // 页面类型

  // 私信按钮
  void _privateLetterClick(
    context,
    id,
    userName,
    avatar,
    token,
  ) {
    SocketState socketState = (state(Global.context, 'socket') as SocketState);
    socketState.goChatPage(
      context,
      id: id,
      token: token,
      name: userName,
      head: avatar,
    );
  }

  /// 关注or粉丝列表单项构造器
  Widget _attentionOrFansListItemBuilder(
    context,
    String token,
    String userName,
    int id,
    String avatar, {
    int gold,
    String sign,
  }) {
    /// 用户动态
    Widget _signatureOrGold() {
      return Container(
        child: Row(
          children: <Widget>[
            Container(
              width: px(32),
              height: px(32),
              margin: EdgeInsets.only(right: px(11)),
              child: Image.asset('assets/images/icon/star.png'),
            ),
            Container(
              child: Text(
                '$gold',
                style: TextStyle(fontSize: px(28), color: col('fea800')),
              ),
            )
          ],
        ),
      );
    }

    /// 通话按钮
    Widget _videoButton(context) {
      return Container(
        height: px(60),
        width: px(120),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(px(30)),
          border: Border.all(color: col('fea800'), width: px(2)),
        ),
        child: FlatButton(
          padding: EdgeInsets.zero,
          onPressed: () {
            showDialog(
              context: context,
              builder: (BuildContext ctx) {
                return dialogBuild(
                  ctx,
                  title: '是否发起与该用户的通话',
                  confirmText: "通话",
                  confirmFn: () {
                    VideoCall.checkUserStatusAndGoVideoPage(context, token);
                  },
                );
              },
            );
          },
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(px(30)),
            ),
          ),
          child: Text(
            '通话',
            style: TextStyle(
              fontSize: px(26),
              color: col('fea800'),
              height: 1.2,
            ),
          ),
        ),
      );
    }

    /// 按钮
    Widget _button(context) {
      return Container(
        height: px(60),
        width: px(120),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(px(30)),
          border: Border.all(color: col('fea800'), width: px(2)),
        ),
        child: FlatButton(
          padding: EdgeInsets.zero,
          onPressed: () {
            _privateLetterClick(
              context,
              id,
              userName,
              avatar,
              token,
            );
          },
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(px(30)),
            ),
          ),
          child: Text(
            '私信',
            style: TextStyle(
              fontSize: px(26),
              color: col('fea800'),
              height: 1.2,
            ),
          ),
        ),
      );
    }

    return Container(
      child: Column(
        children: <Widget>[
          Container(
            height: px(168),
            child: Row(
              children: <Widget>[
                /// 头像
                Container(
                  margin: EdgeInsets.only(right: px(20)),
                  child: Avatar(
                    avatar,
                    true,
                    token: token,
                  ),
                ),

                /// 用户信息
                Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      /// 用户名与ID
                      Container(
                        margin: EdgeInsets.only(bottom: px(10)),
                        child: Text.rich(
                          TextSpan(
                            children: [
                              TextSpan(
                                text: userName + '  ',
                                style: TextStyle(
                                  fontSize: px(28),
                                  color: col('303133'),
                                ),
                              ),
                              TextSpan(
                                text: 'ID:${id.toString()}',
                                style: TextStyle(
                                  fontSize: px(24),
                                  color: col('bfc2cc'),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),

                      /// 签名或粉丝
                      _signatureOrGold()
                    ],
                  ),
                ),

                Spacer(),

                /// 通话按钮
                // Container(
                //   margin: EdgeInsets.only(left: px(20)),
                //   child: _videoButton(context),
                // ),

                /// 按钮
                Container(
                  margin: EdgeInsets.only(left: px(20)),
                  child: _button(context),
                ),
              ],
            ),
          ),

          /// 分割线
          Line(
            margin: EdgeInsets.only(left: px(138)),
          )
        ],
      ),
    );
  }

  UserActivtyBloc bloc;

  @override
  void initState() {
    super.initState();
    bloc = BlocProvider.of<UserActivtyBloc>(context);

    final not = Global.socketNot;
    if (not.value != null) {
      socketNot();
    } else {
      not.addListener(socketNot);
    }
  }

  // 监听有新用户上线
  socketNot() {
    if (Global.socketNot.value == null) return;
    Global.socketNot.value
        .map((str) => jsonDecode(str))
        .where((cls) => cls['datatype'] == 'userlogin')
        .listen(
      (res) {
        bloc.onloadList();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<UserAcitvtyModel>>(
      stream: bloc.outFansStream,
      initialData: [],
      builder: (BuildContext context,
          AsyncSnapshot<List<UserAcitvtyModel>> snapshot) {
        return Container(
          child: EasyRefresh(
            header: EasyRefreshSetting.header,
            footer: EasyRefreshSetting.footer,
            onRefresh: () async {
              bloc.onloadList();
            },
            onLoad: () async {
              bloc.getFansList();
            },
            child: SingleChildScrollView(
              child: Column(
                children: snapshot.data.map<Widget>((item) {
                  return _attentionOrFansListItemBuilder(
                    context,
                    item.memberToken,
                    item.memberNickname,
                    item.id,
                    item.memberHead,
                    gold: item.gold,
                  );
                }).toList(),
              ),
            ),
          ),
        );
      },
    );
  }
}
